package com.fujin.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.fujin.common.To.SkuReductionTo;
import com.fujin.common.To.SpuBoudTo;
import com.fujin.common.Vo.SkuEsModel;
import com.fujin.common.Vo.SkuHasStockVo;
import com.fujin.common.constant.ProductConstant;
import com.fujin.common.utils.R;
import com.fujin.gulimall.product.Vo.*;
import com.fujin.gulimall.product.entity.*;
import com.fujin.gulimall.product.feign.CouponFeign;
import com.fujin.gulimall.product.feign.SearchFeign;
import com.fujin.gulimall.product.feign.WareFeign;
import com.fujin.gulimall.product.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fujin.common.utils.PageUtils;
import com.fujin.common.utils.Query;

import com.fujin.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeign couponFeign;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeign wareFeign;
    @Autowired
    private SearchFeign searchFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and(item -> {
                item.eq("id",key).or().like("spu_name",key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(key) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(key) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("brand_id",brandId);
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(key)){
            wrapper.eq("publish_status",status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.baseMapper.insert(spuInfoEntity);

        //2、保存spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity infoDescEntity = new SpuInfoDescEntity();
        infoDescEntity.setSpuId(spuInfoEntity.getId());
        infoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(infoDescEntity);

        //3、保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        //4、保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect1 = baseAttrs.stream().map((item) -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setSpuId(spuInfoEntity.getId());
            valueEntity.setAttrId(item.getAttrId());
            //根据attrid获取名称
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setAttrValue(item.getAttrValues());
            valueEntity.setQuickShow(item.getShowDesc());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect1);

        //5、保存spu的积分信息 sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoudTo spuBoudTo = new SpuBoudTo();
        BeanUtils.copyProperties(bounds,spuBoudTo);
        spuBoudTo.setSpuId(spuInfoEntity.getId());
        R r1 = couponFeign.saveBound(spuBoudTo);
        if (r1.getCode() != 0){
            log.error("远程调用失败!!!");
        }

        //6、保存当前spu下所有sku信息
        //6.1、sku的基本信息 pms_sku_info
        List<Skus> skus = vo.getSkus();
        if (skus!=null && skus.size() > 0) {
            skus.forEach(item -> {
                //先获取到sku图片
                String defaultUrl = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultUrl = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                //设置默认图片
                skuInfoEntity.setSkuDefaultImg(defaultUrl);
                skuInfoService.savaSkuInfo(skuInfoEntity);

                //6.2、sku的图片信息 pms_sku_images
                List<SkuImagesEntity> collect = item.getImages().stream().map(m -> {
                    SkuImagesEntity imagesEntity = new SkuImagesEntity();
                    imagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    imagesEntity.setImgUrl(m.getImgUrl());
                    imagesEntity.setDefaultImg(m.getDefaultImg());
                    return imagesEntity;
                }).filter(entity -> {
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(collect);

                //6.3、sku的销售属性 pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> valueCollect = attr.stream().map(attrItem -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    attrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    attrValueEntity.setAttrId(attrItem.getAttrId());
                    attrValueEntity.setAttrName(attrItem.getAttrName());
                    attrValueEntity.setAttrValue(attrItem.getAttrValue());
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(valueCollect);

                //6.4、sku的优惠、满减信息 sms_sku_ladder、sms_sku_full_reduction、sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0){
                    R r = couponFeign.saveReduction(skuReductionTo);
                    if (r.getCode() != 0){
                        log.error("远程调用失败!!!");
                    }
                }
            });
        }

    }

    @Override
    public void up(Long spuId) {
        //根据spu查询下面所有sku信息
        List<SkuInfoEntity> skuInfos = skuInfoService.getSkuInfoBySpuId(spuId);
        //过滤得到所有skuId
        List<Long> skuIds = skuInfos.stream().map(item -> {
            return item.getSkuId();
        }).collect(Collectors.toList());

        //TODO 根据spu查出当前sku的所有可以被用来检索的规格属性

        //根据spuId在"spu规格参数表"找到已经关联的规格参数信息
        List<ProductAttrValueEntity> attrValueEntityList = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        //得到所有attrId
        List<Long> attrIds = attrValueEntityList.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        //根据attrId在属性表中查询可以检索的属性
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);

        //将searchAttrIds存入Set结合，
        //通过Set结构、返回所有已经关联的规格参数信息和可以检索的属性集合中存在包含关系的
        Set<Long> ids = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attr> searchAttr = attrValueEntityList.stream().filter(entity -> {
            return ids.contains(entity.getAttrId());
        }).map(item -> {
            //封装返回
            SkuEsModel.Attr attr = new SkuEsModel.Attr();
            BeanUtils.copyProperties(item,attr);
            return attr;
        }).collect(Collectors.toList());

        //TODO 查询是否有库存
        Map<Long, Boolean> skuStockMap = null;
        try {
            R r = wareFeign.getSkuHasStock(skuIds);

            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            //将库存信息转换成一个Map，key为skuId，value为boolean类型的是否有库存，有为true，反之false
            skuStockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("查询库存信息有问题{}",e);
        }


        //遍历skuInfos并封装一个es使用的对象SkuEsModel
        Map<Long, Boolean> finalSkuStockMap = skuStockMap;
        List<SkuEsModel> uProducts = skuInfos.stream().map(sku -> {
            //封装对象SkuEsModel
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            if (finalSkuStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                //根据skuId直接得到是否具有库存
                skuEsModel.setHasStock(finalSkuStockMap.get(sku.getSkuId()));
            }

            //TODO 热度评分。0
            skuEsModel.setHotScore(0L);
            //根据品牌id获取名称
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            //根据分类id获取分类名称
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            skuEsModel.setAttrs(searchAttr);

            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 将数据发送给es进行保存 gulimall-search
        R r = searchFeign.productStatusUp(uProducts);
        if (r.getCode() == 0){
            //远程调用成功
            //调用成功需要将spu上架状态修改为上架
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //远程调用失败
            //TODO 存在问题:重复调用、重试机制
        }

    }

}